<template>
    <!-- 搜索框栏 row1 row2 row3 -->
    <div v-if="look" class="row1">
        <el-row>
            <el-col :span="6">
                <span>客户姓名</span>
                <el-input v-model="ruleForm.name" style="width: 200px" placeholder="请输入客户姓名" />
            </el-col>
            <el-col :span="6">
                <span>客户手机</span>
                <el-input v-model="ruleForm.phone" style="width: 200px" placeholder="请输入客户手机号码" />
            </el-col>
            <el-col :span="6">
                <span>归属人</span>
                <el-input v-model="input" style="width: 200px" placeholder="请输入线索归属人" />
            </el-col>
        </el-row>

    </div>
    <div v-if="look" class="row2">
        <el-row>
            <el-col :span="6">
                <span>渠道来源</span>
                <el-select v-model="ruleForm.channelId" placeholder="渠道来源" style="width: 200px">
                    <el-option v-for="item in options1" :key="item.value" :label="item.channelName"
                        :value="item.channelId" />
                </el-select>
            </el-col>
            <el-col :span="6">
                <span>线索状态</span>
                <el-select v-model="value" placeholder="线索状态" style="width: 200px">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-col>
            <el-col :span="10">
                <span>跟进时间</span>
                <el-date-picker v-model="value1" type="datetimerange" range-separator="To"
                    start-placeholder="Start date" end-placeholder="End date" />
            </el-col>
        </el-row>

    </div>
    <div v-if="look" class="row3">
        <el-button type="primary" :icon="Search">搜索</el-button>
        <el-button :icon="Refresh">重置</el-button>
    </div>
    <!-- 点击放大镜按钮 搜索栏隐藏  刷新按钮就是重新调用列表渲染的接口 getlist！-->
    <div class="row3 row4">
        <div>
            <el-button type="primary" plain :icon="Plus" @click="add">新增</el-button>
            <el-button type="success" plain :icon="Edit" :disabled="isEditDisabled" @click="edit">修改</el-button>
            <el-button type="danger" plain :icon="Delete" :disabled="isdelDisabled" @click="del">删除</el-button>
        </div>
        <div>
            <el-button :icon="Search" circle @click="look = !look" />
            <el-button :icon="Refresh" circle @click="getlist" />
        </div>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 96%;margin-top: 15px;margin-left: 20px;"
        @selection-change="handleSelectionChange" ref="multipleTableRef">

        <el-table-column type="selection" width="55" />

        <el-table-column property="clueId" label="线索编号" width="100" />

        <el-table-column property="name" label="客户姓名" width="100" />
        <el-table-column property="phone" label="手机号码" width="110" show-overflow-tooltip />
        <el-table-column property="channelName" label="渠道来源" width="120" />
        <el-table-column label="创建时间" width="160" property="createTime">
        </el-table-column>
        <el-table-column property="owner" label="线索归属" />
        <el-table-column prop="tag" label="线索状态" width="100">
            <template #default="scope">
                <el-tag v-if="scope.row.status == 1">已分配</el-tag>
                <el-tag v-if="scope.row.status == 2" type="success">跟进中</el-tag>
                <el-tag v-if="scope.row.status == 3" type="info">回收</el-tag>
                <el-tag v-if="scope.row.status == 4" type="warning">伪线索</el-tag>
                <el-tag v-if="scope.row.status == 0" type="danger">未知</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="下次跟进时间" width="160" property="nextTime">
        </el-table-column>
        <el-table-column label="操作" width="140">
            <template #default="scope">
                <el-button link type="primary" size="small" :icon="Pointer" @click="jump(scope.row.clueId)">
                    跟进
                </el-button>
                <el-button link type="primary" size="small" :icon="TopRight" @click="tree">分配</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]"
        :size="query.pageSize" :disabled="disabled" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <!-- 新增对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="650">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="ruleForm.phone" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户姓名" prop="name">
                        <el-input v-model="ruleForm.name" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="渠道来源" prop="channelId">
                        <el-select v-model="ruleForm.channelId" placeholder="渠道来源" @click="getChannel">
                            <!-- <el-option label="Zone one" value="shanghai" />
                            <el-option label="Zone two" value="beijing" /> -->
                            <el-option v-for="item in options1" :key="item.channelId" :label="item.channelName"
                                :value="item.channelId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="活动信息">
                        <el-select v-model="ruleForm.activityId" placeholder="活动信息" @click="getActivity">
                            <!-- <el-option label="Zone one" value="shanghai" />
                            <el-option label="Zone two" value="beijing" /> -->
                            <el-option v-for="item in options2" :key="item.value" :label="item.name"
                                :value="item.activityId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="客户性别">
                        <el-radio-group v-model="ruleForm.gender">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                            <el-radio :label="2">未知</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户年龄" prop="age">
                        <el-input-number v-model="ruleForm.age" :min="6" :max="100" placeholder="年龄" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="微信号" prop="weixin">
                        <el-input v-model="ruleForm.weixin" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="QQ号" prop="qq">
                        <el-input v-model="ruleForm.qq" />
                    </el-form-item>
                </el-col>
            </el-row>
            <div style="text-align: right;">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </div>
        </el-form>

    </el-dialog>
    <!-- 删除数据 确认对话框 -->
    <el-dialog v-model="deldialogVisible" title="Tips" width="500" destroy-on-close>
        <p>是否确认删除线索编号为<span v-for="items in multipleSelection">{{ items.clueId }},</span>的数据项？</p>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="deldialogVisible = false">取消</el-button>
                <el-button type="primary" @click="delsubmit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 分配 -->
    <el-dialog v-model="dialogtree" title="分配线索" width="650">
        <el-row :gutter="20">
            <el-col :span="14">
                <span>归属部门</span>
                <el-tree-select v-model="selectedNodeId" :data="treedata" :props="treeProps" @change="handleDeptChange"
                    :render-after-expand="false" style="width: 200px" check-strictly placeholder="请选择归属部门" />
            </el-col>
            <el-col :span="10">
                <span>分配给</span>
                <el-select v-model="selectedUserId" @change="handleUserChange" placeholder="Select"
                    style="width: 200px">
                    <el-option v-for="item in assignOptions" :key="item.userId" :label="item.nickName"
                        :value="item.userId" />
                </el-select>
            </el-col>
        </el-row>
        <div style="text-align: right;margin-top: 30px;">
            <el-button type="primary" @click="confirm">确定</el-button>
            <el-button @click="dialogtree = false">取消</el-button>

        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { useGlobalClueId } from './globalClueId'; // 引入全局变量模块
import { reactive, ref, nextTick, computed } from 'vue';
import { showData, addData, channelData, activityData, editData, editSuccess, delSuccess, treeSelect, treeAssign, assignment, serach } from '@/api/clue/clues';
import { Search, Refresh, Delete, Plus, Edit, Pointer, TopRight } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
const deldialogVisible = ref(false);
const dialogtree = ref(false);
const statusOptions = ref([{ label: "未知", value: 0 }, { label: "已分配", value: 1 }, { label: "跟进中", value: 2 }, { label: "回收", value: 3 }, { label: "伪线索", value: 4 }]);
let assignOptions: any = ref([])
let treedata: any = ref([])
const query = reactive({
    pageNum: 1,
    pageSize: 10
});
const total = ref();
const input = ref('');
const value = ref('');
let look = ref(true);

const value1 = ref<[Date, Date]>([
    new Date(2000, 10, 10, 10, 10),
    new Date(2000, 10, 11, 10, 10),
]);

let tableData: any = ref([]);


//分页
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const background = ref(false);
const disabled = ref(false);
function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    query.pageSize = val;
    getlist();
}
function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    query.pageNum = val;
    getlist();
}
let options1: any = ref([{}])
//渲染表格数据
function getlist() {
    showData(query).then(res => {
        console.log(res);
        tableData.value = res.rows
        // tableData.value = res.rows.map(item => {
        //     return {
        //         clueId: item.clueId || null,
        //         name: item.name || '',
        //         phone: item.phone || '',
        //         channelName: item.channelName || '',
        //         createTime: item.createTime || '',
        //         nextTime: item.nextTime || '',
        //         owner: item.owner || '',
        //         status: item.status || ''
        //     };
        // });
        total.value = res.total

        // console.log('tableData:', tableData.value);
        // console.log('total:', total.value);


    });
    channelData(options1).then(res => {
        console.log(res);
        ruleForm.channelId = res.data.channelId;
        options1.value = res.data;

    });
}
getlist();

// 新增一个选中数据数组
let multipleSelection = ref([]);
// 新增一个是否禁用修改按钮的计算属性
const isEditDisabled = computed(() => {
    return multipleSelection.value.length !== 1;
});
const isdelDisabled = computed(() => {
    return multipleSelection.value.length === 0;
});
// 新增一个表格选中状态变化处理函数
let clue: any = reactive([])
// let clueLast = ref();
const { clueLast } = useGlobalClueId(); // 使用全局的 clueLast
let ids = ref();
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val;
    clue = JSON.parse(JSON.stringify(val));
    ids.value = clue[0];
    console.log(ids.value);
    // clueLast.value = clue[0].clueId;
    clueLast.value = clue[0]?.clueId; // 更新全局的 clueLast
    console.log(clueLast.value);//ref对象！！！
};


interface RuleForm {
    name: string
    phone: string
    qq: string
    weixin: string
    age: number
    gender: number
    channelId: number
    activityId: number
}

let ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
    name: '',
    phone: '',
    qq: '',
    weixin: '',
    age: 6,
    gender: 0,
    channelId: 1,
    activityId: 1
});

let options2: any = ref([{}])
let dialogVisible = ref(false);



//新增对话框：获取渠道来源
function getChannel() {
    channelData(ruleForm.channelId).then(res => {
        console.log(res);
        ruleForm.channelId = res.data.channelId;
        options1.value = res.data;

    });
}
//新增对话框：获取活动信息
function getActivity() {
    activityData(ruleForm.channelId).then(res => {
        console.log(res);
        options2.value = res.data;
    });
}
//校验表格
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入客户手机号码', trigger: 'blur' }
    ]
});
let title = ref('');
const multipleTableRef = ref();

//新增数据提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === '新增') {
                addData(ruleForm).then(res => {
                    console.log(res);
                });
                dialogVisible.value = false;
                getlist();
                ElMessage({
                    type: 'success',
                    message: '新增成功',
                });

            } else {
                if (!currentEditId.value) {
                    ElMessage.error("缺少线索ID");
                    return;
                }
                const params = {
                    ...ruleForm,
                    clueId: currentEditId.value // 确保传递正确ID
                };
                editSuccess(params).then(res => {
                    console.log(res);
                    multipleTableRef.value?.clearSelection();
                    multipleSelection.value = [];
                    dialogVisible.value = false;
                    getlist();
                    ElMessage.success("修改线索成功！");
                });


            }

        } else {
            console.log('error submit!', fields);
        }
    });
};

console.log(tableData);

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
};


//新增数据
function add() {
    dialogVisible.value = true;
    title.value = "新增";
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
}
let currentEditId = ref<number | null>(null); // 新增：专门存储当前编辑ID
//修改数据
function edit() {
    if (multipleSelection.value.length !== 1) return;
    const selection = multipleSelection.value[0];
    currentEditId.value = selection.clueId; // 直接使用选中项ID
    dialogVisible.value = true;
    title.value = "修改线索";
    editData(clueLast.value).then(res => {
        console.log(res);
        ruleForm.phone = res.data.phone;
        ruleForm.name = res.data.name;
        ruleForm.channelId = res.data.channelId;
        ruleForm.activityId = res.data.activityId;
        ruleForm.gender = res.data.gender;
        ruleForm.weixin = res.data.weixin;
        ruleForm.qq = res.data.qq;
    });
}
//删除数据
function del() {
    deldialogVisible.value = true

}
function delsubmit() {
    const ids = multipleSelection.value.map(item => item.clueId);
    delSuccess(ids).then(res => {
        console.log(res);

        getlist();
        deldialogVisible.value = false;
        ElMessage.success("删除成功！！");
    });
    multipleTableRef.value?.clearSelection();
    multipleSelection.value = [];
    // delSuccess([clueLast.value]).then(res => {
    //     console.log(res);
    // });

}
// 定义树形选择器的字段映射（根据后端数据格式调整）
const treeProps = reactive({
    value: 'id',        // 节点值的字段名，这里我们使用id作为值
    label: 'label',     // 节点标签的字段名
    children: 'children' // 子节点的字段名
});
let objtree = ref({
    assignId: null,
    deptId: null,
    userId: null,
    userName: ""
});
let selectedUserId = ref(null);
function handleUserChange(userId: any) {
    objtree.value.userId = userId; // 将选中的用户ID赋值给 objtree
    // 2. 根据userId找到对应的用户对象
    const selectedUser = assignOptions.value.find((item: any) => item.userId === userId);

    // 3. 同步userName（若找到用户则赋值nickName，否则清空）
    objtree.value.userName = selectedUser ? selectedUser.userName : "";
}

function handleDeptChange(deptId: any) {
    objtree.value.deptId = deptId; // 将选中的部门ID赋值给 objtree
}
// 绑定选中的节点ID（用于获取用户选择的部门）
const selectedNodeId = ref<number | string>(null);
//分配按钮
function tree() {
    dialogtree.value = true;
    treeSelect().then(res => {
        console.log(res);
        treedata.value = res.data;
        console.log(treedata.value);

    });
    treeAssign().then(res => {
        console.log(res);
        assignOptions.value = res.data;
    });
    if (multipleSelection.value.length === 1) {
        objtree.value.assignId = multipleSelection.value[0].clueId;
    }
}

function confirm() {
    assignment(objtree.value).then(res => {
        console.log(res);
        multipleTableRef.value?.clearSelection();
        multipleSelection.value = [];
        dialogtree.value = false;
        ElMessage.success("分配成功！");
    });
}
//路由跳转
import router from '@/router';

function jump(clueId: any) {
    console.log('当前行线索ID:', clueId);

    //     router.push({ path: `/clue/details/index/${clueLast.value}/follow` });

    router.push({ path: `/clue/details/index/${clueId}/follow`, query: { clueId } });

}
</script>

<style lang="scss" scoped>
.row1,
.row2 {
    margin-top: 15px;
    margin-left: 20px;

    .el-row {
        .el-col {
            span {
                display: inline-block;
                font-size: 14px;
                padding-right: 10px;
                font-weight: bold;
                color: rgba($color: #000000, $alpha: 0.6);
            }
        }
    }
}

.row3 {
    margin-top: 15px;
    margin-left: 20px;

}

.row4 {
    display: flex;
    justify-content: space-between;
    width: 96%;
}

.el-pagination {
    margin-top: 20px;
    margin-left: 100px;
}
</style>